// pass: 30.7%
function maxWater(height) {
    let max = 0;
    let n = height.length;

    for (let i = 0; i < n; i++) {
        let maxRight = height[i];
        let maxRightIndex = i;
        let leftHeight = height[i];
        let left = i;
        for (let j = i + 1; j < n; j++) {
            if (maxRight <= height[j] && maxRight >= leftHeight) {
                i = left - 1;
                break;
            }
            maxRight = Math.max(maxRight, height[j]);
            if (height[j] < maxRight) {
                i = maxRightIndex - 1;
                break;
            }
            if (height[j] === maxRight && leftHeight <= height[j] && (j - i > 1)) {
                maxRightIndex = j;
                let sum = Math.min(height[i], height[j]) * (j - i);
                for (let k = i + 1; k < j; k++) {
                    sum -= height[k];
                }
                max = Math.max(max, sum);
            }
        }
    }

    return max;
}

let height = [4, 3, 2, 1, 3, 0, 5, 0, 1];
console.log(maxWater(height))